﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Film.Common;

namespace Film.Repository
{
    public class tblRatingRepository : Repository<tblRating>
    {
        public int AddList(List<tblRating> lst, int uId)
        {
            try
            {
                var _movie = dataContext.tblRatings;
                foreach (tblRating item in lst)
                {
                    var obj = _movie.Where(c => c.MovieID == item.MovieID && c.UserID== uId).FirstOrDefault();
                    if (obj != null)
                    {
                        obj.Rating = item.Rating;
                        obj.Status = item.Status;
                    }
                    else
                    {
                        dataContext.tblRatings.InsertOnSubmit(item);
                    }
                }
                //
                //dataContext.tblRatings.InsertAllOnSubmit(lst);
                dataContext.SubmitChanges();
                //Sum movie
                foreach (tblRating item in lst)
                {
                    var objM = dataContext.tblMovies.Where(c => c.MovieID == item.MovieID).FirstOrDefault();
                    if (objM != null)
                    {
                        var objRat = dataContext.tblRatings.Where(c => c.MovieID == item.MovieID).ToList();
                        objM.SumRating = Convert.ToInt32(objRat.Sum(c => c.Rating));
                        objM.TotalRating = objRat.Count();
                    }
                }
                //
                dataContext.SubmitChanges();
                return 1;
            }
            catch (Exception)
            {
                return -1;
            }
        }
        /// <summary>
        /// Lay Rating by MovieID
        /// </summary>
        /// <param name="movieID"></param>
        /// <returns></returns>
        public List<tblRating> GetRatingByMovieID(int movieID)
        {
            return dataContext.tblRatings.Where(x => x.MovieID == movieID).ToList();
        }
        public List<tblRating> GetRatingByUserID(int userID)
        {
            return dataContext.tblRatings.Where(x => x.UserID == userID).ToList();
        }

        public List<tblRating> GetRatingByMovieIDAndAgeID(int movieID, int ageID)
        {
            var result = (from ds in dataContext.tblRatings
                          join qd in dataContext.tblUsers
                          on ds.UserID equals qd.UserID
                          join ag in dataContext.tblAges 
                          on qd.AgeID equals ag.AgeID
                          where ds.MovieID == movieID && ag.AgeID == ageID
                          select ds);

            return result.ToList();
        }
    }
}
